package com.ecommerce.service;

import com.ecommerce.dao.CategoryDAO;
import com.ecommerce.dao.ProductDAO;
import com.ecommerce.model.Category;
import com.ecommerce.model.Product;
import com.ecommerce.model.User;
import com.ecommerce.util.InputUtil;
import java.util.List;

public class ProductService {
    private ProductDAO productDAO;
    private CategoryDAO categoryDAO;

    public ProductService() {
        this.productDAO = new ProductDAO();
        this.categoryDAO = new CategoryDAO();
    }

    // 顾客浏览商品（只显示上架商品）
    public void browseProductsForCustomer() {
        List<Product> products = productDAO.getActiveProducts();
        System.out.println("\n=== 商品浏览 ===");
        if (products.isEmpty()) {
            System.out.println("暂无商品");
        } else {
            for (Product product : products) {
                System.out.println(product);
            }
        }
        System.out.println("总计: " + products.size() + " 件商品");
        System.out.println("===============");
    }

    // 管理员查看所有商品
    public void displayAllProductsForAdmin() {
        List<Product> products = productDAO.getAllProducts();
        System.out.println("\n=== 所有商品（管理员视图） ===");
        if (products.isEmpty()) {
            System.out.println("暂无商品");
        } else {
            for (Product product : products) {
                String status = "active".equals(product.getStatus()) ? "[上架]" : "[下架]";
                System.out.println(status + " " + product);
            }
        }
        System.out.println("总计: " + products.size() + " 件商品");
        System.out.println("===============");
    }

    public void displayProductDetailsForCustomer() {
        System.out.println("\n=== 查看商品详情 ===");
        browseProductsForCustomer();

        int productId = InputUtil.getIntInput("请输入商品ID: ");
        Product product = productDAO.getActiveProductById(productId);

        if (product != null) {
            System.out.println("\n=== 商品详情 ===");
            System.out.println(product.toDetailedString());
        } else {
            System.out.println("商品不存在或已下架！");
        }
    }

    public void displayProductDetailsForAdmin() {
        System.out.println("\n=== 查看商品详情 ===");
        displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入商品ID: ");
        Product product = productDAO.getProductById(productId);

        if (product != null) {
            System.out.println("\n=== 商品详情 ===");
            System.out.println(product.toDetailedString());
        } else {
            System.out.println("商品不存在！");
        }
    }

    public void addProduct() {
        System.out.println("\n=== 添加商品 ===");

        // 显示所有分类
        List<Category> categories = categoryDAO.getAllCategories();
        System.out.println("可选分类:");
        for (Category category : categories) {
            System.out.println(category);
        }

        String name = InputUtil.getStringInput("商品名称: ");
        String description = InputUtil.getStringInput("商品描述: ");
        double price = InputUtil.getDoubleInput("商品价格: ");
        int stockQuantity = InputUtil.getIntInput("库存数量: ");
        int categoryId = InputUtil.getIntInput("分类ID: ");

        // 验证分类是否存在
        Category category = categoryDAO.getCategoryById(categoryId);
        if (category == null) {
            System.out.println("分类不存在！");
            return;
        }

        Product product = new Product(name, description, price, stockQuantity, categoryId);
        boolean success = productDAO.addProduct(product);

        if (success) {
            System.out.println("商品添加成功！");
        } else {
            System.out.println("商品添加失败！");
        }
    }

    public void updateProduct() {
        System.out.println("\n=== 更新商品 ===");
        displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入要更新的商品ID: ");
        Product existingProduct = productDAO.getProductById(productId);

        if (existingProduct == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("当前商品信息:");
        System.out.println(existingProduct.toDetailedString());

        // 显示所有分类
        List<Category> categories = categoryDAO.getAllCategories();
        System.out.println("可选分类:");
        for (Category category : categories) {
            System.out.println(category);
        }

        String name = InputUtil.getStringInput("新商品名称 (留空保持不变): ");
        String description = InputUtil.getStringInput("新商品描述 (留空保持不变): ");
        String priceInput = InputUtil.getStringInput("新价格 (留空保持不变): ");
        String stockInput = InputUtil.getStringInput("新库存数量 (留空保持不变): ");
        String categoryInput = InputUtil.getStringInput("新分类ID (留空保持不变): ");

        // 更新字段
        if (!name.isEmpty()) existingProduct.setName(name);
        if (!description.isEmpty()) existingProduct.setDescription(description);
        if (!priceInput.isEmpty()) existingProduct.setPrice(Double.parseDouble(priceInput));
        if (!stockInput.isEmpty()) existingProduct.setStockQuantity(Integer.parseInt(stockInput));
        if (!categoryInput.isEmpty()) {
            int newCategoryId = Integer.parseInt(categoryInput);
            Category category = categoryDAO.getCategoryById(newCategoryId);
            if (category != null) {
                existingProduct.setCategoryId(newCategoryId);
            } else {
                System.out.println("分类不存在，分类保持不变");
            }
        }

        boolean success = productDAO.updateProduct(existingProduct);
        if (success) {
            System.out.println("商品更新成功！");
        } else {
            System.out.println("商品更新失败！");
        }
    }

    public void toggleProductStatus() {
        System.out.println("\n=== 商品上下架 ===");
        displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入要操作的商品ID: ");
        Product product = productDAO.getProductById(productId);

        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        String currentStatus = "active".equals(product.getStatus()) ? "上架" : "下架";
        String newStatus = "active".equals(product.getStatus()) ? "下架" : "上架";

        System.out.println("当前状态: " + currentStatus);
        String confirm = InputUtil.getStringInput("确认" + newStatus + "此商品？(y/N): ");

        if ("y".equalsIgnoreCase(confirm)) {
            boolean success = productDAO.toggleProductStatus(productId);
            if (success) {
                System.out.println("商品" + newStatus + "成功！");
            } else {
                System.out.println("操作失败！");
            }
        } else {
            System.out.println("取消操作");
        }
    }

    public void displayProductsByCategoryForCustomer() {
        System.out.println("\n=== 按分类查看商品 ===");
        List<Category> categories = categoryDAO.getAllCategories();
        System.out.println("所有分类:");
        for (Category category : categories) {
            System.out.println(category);
        }

        int categoryId = InputUtil.getIntInput("请输入分类ID: ");
        List<Product> products = productDAO.getProductsByCategory(categoryId, false);

        Category category = categoryDAO.getCategoryById(categoryId);
        String categoryName = category != null ? category.getName() : "未知分类";

        System.out.println("\n=== " + categoryName + "分类商品 ===");
        if (products.isEmpty()) {
            System.out.println("该分类下暂无上架商品");
        } else {
            for (Product product : products) {
                System.out.println(product);
            }
        }
        System.out.println("总计: " + products.size() + " 件商品");
        System.out.println("===============");
    }

    public void displayProductsByCategoryForAdmin() {
        System.out.println("\n=== 按分类查看商品 ===");
        List<Category> categories = categoryDAO.getAllCategories();
        System.out.println("所有分类:");
        for (Category category : categories) {
            System.out.println(category);
        }

        int categoryId = InputUtil.getIntInput("请输入分类ID: ");
        List<Product> products = productDAO.getProductsByCategory(categoryId, true);

        Category category = categoryDAO.getCategoryById(categoryId);
        String categoryName = category != null ? category.getName() : "未知分类";

        System.out.println("\n=== " + categoryName + "分类商品 ===");
        if (products.isEmpty()) {
            System.out.println("该分类下暂无商品");
        } else {
            for (Product product : products) {
                String status = "active".equals(product.getStatus()) ? "[上架]" : "[下架]";
                System.out.println(status + " " + product);
            }
        }
        System.out.println("总计: " + products.size() + " 件商品");
        System.out.println("===============");
    }

    public void browseProductsForCustomerMenu() {
        while (true) {
            System.out.println("\n=== 浏览商品 ===");
            System.out.println("1. 查看所有商品");
            System.out.println("2. 按分类查看商品");
            System.out.println("3. 查看商品详情");
            System.out.println("4. 返回上级菜单");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    browseProductsForCustomer();
                    break;
                case 2:
                    displayProductsByCategoryForCustomer();
                    break;
                case 3:
                    displayProductDetailsForCustomer();
                    break;
                case 4:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }

    public void deleteProduct() {
        System.out.println("\n=== 删除商品 ===");
        displayAllProductsForAdmin();

        int productId = InputUtil.getIntInput("请输入要删除的商品ID: ");
        Product product = productDAO.getProductById(productId);

        if (product == null) {
            System.out.println("商品不存在！");
            return;
        }

        System.out.println("要删除的商品信息:");
        System.out.println(product.toDetailedString());

        // 双重确认
        System.out.println("\n警告：此操作将永久删除商品，无法恢复！");
        String confirm1 = InputUtil.getStringInput("确认删除？请输入 'DELETE' 确认: ");
        if (!"DELETE".equals(confirm1)) {
            System.out.println("取消删除");
            return;
        }

        String confirm2 = InputUtil.getStringInput("再次确认，请输入商品名称 '" + product.getName() + "': ");
        if (!product.getName().equals(confirm2)) {
            System.out.println("商品名称不匹配，取消删除");
            return;
        }

        boolean success = productDAO.deleteProductPermanently(productId);
        if (success) {
            System.out.println("商品删除成功！");
        } else {
            System.out.println("商品删除失败！");
        }
    }

    public void manageProducts() {
        while (true) {
            System.out.println("\n=== 商品管理 ===");
            System.out.println("1. 查看所有商品");
            System.out.println("2. 添加商品");
            System.out.println("3. 更新商品");
            System.out.println("4. 商品上下架");
            System.out.println("5. 删除商品");
            System.out.println("6. 按分类查看商品");
            System.out.println("7. 查看商品详情");
            System.out.println("8. 返回上级菜单");

            int choice = InputUtil.getIntInput("请选择操作: ");

            switch (choice) {
                case 1:
                    displayAllProductsForAdmin();
                    break;
                case 2:
                    addProduct();
                    break;
                case 3:
                    updateProduct();
                    break;
                case 4:
                    toggleProductStatus();
                    break;
                case 5:
                    deleteProduct();
                    break;
                case 6:
                    displayProductsByCategoryForAdmin();
                    break;
                case 7:
                    displayProductDetailsForAdmin();
                    break;
                case 8:
                    return;
                default:
                    System.out.println("无效选择，请重新输入！");
            }
        }
    }
}